package com.littleken.dao.impl;

import com.littleken.dao.UserDao;
import com.littleken.entity.User;
import com.littleken.utils.SqlUtil;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class UserUserDaoImpl implements UserDao {
    /**
     * 查询全部User
     * @return List<User>,没有和出错返回Null
     */
    @Override
    public List<User> getAllUser(){
        List<User> lists = new ArrayList<>();
        User user = null;
        try{
            ResultSet resultSet = SqlUtil.getResultSet("select * from user");
            while(resultSet.next()){
                Integer id = resultSet.getInt(1);
                String username = resultSet.getString(2);
                String password = resultSet.getString(3);
                Integer sex = resultSet.getInt(4);
                String telephone = resultSet.getString(5);
                String mail = resultSet.getString(6);
                user = new User(id,username,password,sex,telephone,mail);
                lists.add(user);
            }
        }catch (Exception e){
            System.out.println("userDao类getAllUser()出错");
        }
       return lists;
    }

    /**
     * 根据id查用户
     * @param id
     * @return User 没有和出错返回Null
     */
    @Override
    public User getUserById(int id){
        User user = null;
        try{
            ResultSet resultSet = SqlUtil.getResultSet("select * from user where id="+id);
            if(resultSet.next()){
                Integer uid = resultSet.getInt(1);
                String username = resultSet.getString(2);
                String password = resultSet.getString(3);
                Integer sex = resultSet.getInt(4);
                String telephone = resultSet.getString(5);
                String mail = resultSet.getString(6);
                user = new User(uid,username,password,sex,telephone,mail);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return user;
    }

    /**
     * 根据name查用户
     * @param name
     * @return User 没有和出错返回Null
     */
    @Override
    public User getUserByUsername(String name) {
        User user = null;
        try{
            ResultSet resultSet = SqlUtil.getResultSet("select * from user where username='"+name+"'");
            if(resultSet.next()){
                Integer uid = resultSet.getInt(1);
                String username = resultSet.getString(2);
                String password = resultSet.getString(3);
                Integer sex = resultSet.getInt(4);
                String telephone = resultSet.getString(5);
                String mail = resultSet.getString(6);
                user = new User(uid,username,password,sex,telephone,mail);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return user;
    }
}
